﻿using System.ComponentModel.DataAnnotations;

namespace RuoVea.ExUtil.Validate;

/// <summary>
/// 描 述：最大长度
/// </summary>
public class MaxWordsAttribute : ValidationAttribute
{
    private readonly int _maxWords;

    /// <summary>
    /// 构造函数
    /// </summary>
    /// <param name="maxWords">长度</param>
    public MaxWordsAttribute(int maxWords)
    {
        _maxWords = maxWords;
        this.ErrorMessage = $"{{0}}字符长度最大为{maxWords}";
    }

    /// <summary>
    /// 构造函数
    /// </summary>
    /// <param name="maxWords">最大长度</param>
    /// <param name="msg">提示内容</param>
    public MaxWordsAttribute(int maxWords, string msg)
    {
        _maxWords = maxWords;
        this.ErrorMessage = $"{msg}最大为{maxWords}";
    }

    /// <summary>
    /// 证请求结果
    /// </summary>
    /// <param name="value">校验内容</param>
    /// <param name="validationContext">报错指定对象</param>
    /// <returns>证请求结果的容器</returns>
    protected override ValidationResult IsValid(object value, ValidationContext validationContext)
    {
        if (value != null)
        {
            var valueAsString = value.ToString();
            if (valueAsString.Length > _maxWords)
            {
                //FormatErrorMessage方法会自动使用显示的属性名称来格式化这个字符串
                var errorMessage = FormatErrorMessage(validationContext.DisplayName);
                return new ValidationResult(errorMessage);
            }
        }
        return ValidationResult.Success;
    }
}
